package edu.mtu.citizenscience.ethnography.util;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import edu.mtu.citizenscience.ethnography.R;
import edu.mtu.citizenscience.ethnography.uploader.EthnographyUploadService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.location.Location;
import android.widget.TextView;

public class Util {

	public static final String ID_KEY = "interviewID";
	public static final String PHOTO_KEY = "photoName";
	
	public static final String PREFS_KEY = "prefs";
	
    public static final String API_KEY_DEFAULT = "jaF8ibs3AYFcODFkfGD75mSkNaMVVs90O1OvxVe0";
	
	public static final String PREFS_API_KEY = "api key";
	public static final String PREFS_USERNAME = "username";
	
	public static Map<String, Integer> loginStringIDs;

	static {
		loginStringIDs = new HashMap<String, Integer>();
		loginStringIDs.put(EthnographyUploadService.RESULT_SUCCESS, R.string.login_success);
		loginStringIDs.put(EthnographyUploadService.RESULT_FAILURE, R.string.login_failure);
		loginStringIDs.put(EthnographyUploadService.RESULT_ERROR, R.string.login_error);
	}

	public static void showErrorDialog(final Activity activity, String message) {
		if (activity != null) {

			AlertDialog.Builder builder = new AlertDialog.Builder(activity);
			builder.setPositiveButton(R.string.uploadOK, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.setMessage(message);
			builder.create().show();
		} else {
			throw new IllegalArgumentException("showCreationFailedMessage: activity must not be null");
		}
	}

	public static void formatLocationField(TextView tv, Location l) {
		if (l != null) {
			String text = Location.convert(l.getLatitude(), Location.FORMAT_SECONDS) +
					", " + Location.convert(l.getLongitude(), Location.FORMAT_SECONDS);
			tv.setTypeface(null, Typeface.NORMAL);
			tv.setText(text);
		} else {
			tv.setTypeface(null, Typeface.ITALIC);
			tv.setText(R.string.location_default);
		}

	}

	// Copied from http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
	public static int calculateInSampleSize(
			BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and width
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the larger ratio as inSampleSize value, this will guarantee
			// a final image with both dimensions smaller than or equal to the
			// requested height and width.
			inSampleSize = heightRatio > widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}
	
	// Copied and adapted from http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
	public static Bitmap decodeSampledBitmapFromFile(String pathName,
	        int reqWidth, int reqHeight) {

	    // First decode with inJustDecodeBounds=true to check dimensions
	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(pathName, options);

	    // Calculate inSampleSize
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;
	    return BitmapFactory.decodeFile(pathName, options);
	}
	
	public static boolean isLoggedIn(Context context) {
		SharedPreferences prefs = context.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
		boolean result = prefs.contains(PREFS_API_KEY) && prefs.contains(PREFS_USERNAME);
		
		return result;
	}
	
	public static class LocationTriple {
		public int degrees;
		public int minutes;
		public double seconds;
		
		public LocationTriple() {
			this(0);
		}
		
		public LocationTriple(double locationCoord) {
			Double temp = locationCoord;
			degrees = temp.intValue();
			temp = (temp - degrees) * 60;
			minutes = Math.abs(temp.intValue());
			seconds = Math.abs((temp - minutes) * 60);
		}
		
		public double doubleValue() {
			double result = degrees;
			if (degrees >= 0.0) {
				result += ((double)minutes) / 60 + seconds / 3600;
			} else {
				result -= ((double)minutes) / 60 + seconds / 3600;
			}
			
			return result;
		}
	}
	
	public static String formatTimeWithHours(long time) {
		long totalSeconds = time / 1000;
		long hours = totalSeconds / 3600;
		long minutes = (totalSeconds % 3600) / 60;
		long seconds = totalSeconds % 60;
		String returnStr = String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds);
		return returnStr;
	}
	
	public static String formatTimeNoHours(long time) {
		long totalSeconds = time / 1000;
		long minutes = totalSeconds / 60;
		long seconds = totalSeconds % 60;
		String returnStr = String.format(Locale.US, "%02d:%02d", minutes, seconds);
		return returnStr;
	}
	
	public static boolean isOverOneHour(long timeMillis) {
		return (timeMillis / 1000) > 3600;
	}
}
